#include <NewPing.h>

#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define BUZZER_PIN 4

NewPing sonar(TRIGGER_PIN, ECHO_PIN);
const int alarmDistance = 50;

int melody[] = {
  262, 262, 392, 392, 440, 440,
  392, 349, 349, 330, 330, 294,
  294, 262
};

int noteDurations[] = {
  4, 4, 4, 4, 4, 4,
  2, 4, 4, 4, 4, 4,
  2, 4
};

void setup() {
  pinMode(BUZZER_PIN, OUTPUT);
}

void loop() {
  int distance = sonar.ping_cm();
  if (distance > alarmDistance) {
    playMelody();
  }
}

void playMelody() {
  for (int i = 0; i < sizeof(melody) / sizeof(melody[0]); i++) {
    int noteDuration = 1000 / noteDurations[i];
    buzz(BUZZER_PIN, melody[i], noteDuration);
    delay(noteDuration * 1.3);
    noBuzz(BUZZER_PIN);
    delay(noteDuration * 0.3);
  }
}

void buzz(int targetPin, long frequency, long length) {
  long delayValue = 1000000 / frequency / 2;
  long numCycles = frequency * length / 1000;
  
  for (long i = 0; i < numCycles; i++) {
    digitalWrite(targetPin, HIGH);
    delayMicroseconds(delayValue);
    digitalWrite(targetPin, LOW);
    delayMicroseconds(delayValue);
  }
}

void noBuzz(int targetPin) {
  digitalWrite(targetPin, LOW);
}





